package com.keyinong.fragment;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.keyinong.bluetooth.BluetoothActivity;
import com.keyinong.qudan.R;
import com.keyinong.qudan.ScanActivity;
import com.keyinong.qudan.entity.OrderEntity;
import com.keyinong.qudan.tools.CustomDialog;
import com.keyinong.qudan.tools.HttpTools;
import com.keyinong.qudan.tools.NetWorkUtil;
import com.keyinong.qudan.tools.CustomDialog.DialogClickListener;
import com.keyinong.qudan.view.MainActivity;
import com.keyinong.qudan.view.OrderDetailActivity;
import com.keyinong.wifiprint.WifiPrintActivity;
import com.loopj.android.http.JsonHttpResponseHandler;

public class ShouyeFragment extends Fragment{
	View iscatview = null;
	private static String TAG = MainActivity.class.getSimpleName(); 	
	/**上下拉刷新*/
	private PullToRefreshListView list_order;
	HttpTools httpTools = null;
	private ArrayList<OrderEntity> orderlist;
	private OrderAdapter adapter;
	
	int page = 10;
	int offset = 0;
	private String token;
	private String state;
	/**扫一扫*/
	private ImageButton btn_saoyisao;
	private TextView tv_dingdan;
	private Context mContext;
	
	// 语音合成对象
		private SpeechSynthesizer mTts;
		// 默认发音�?
		private String voicer = "xiaoyan";
		private String[] mCloudVoicersEntries;
		private String[] mCloudVoicersValue ;
		private Toast mToast;
		// 引擎类型
		private String mEngineType = SpeechConstant.TYPE_CLOUD;

		private SharedPreferences mSharedPreferences;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mContext=getActivity();
		return inflater.inflate(R.layout.fragment_shouye, null);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		orderlist = new ArrayList<OrderEntity>();
		tv_dingdan=(TextView)getView().findViewById(R.id.tv_dingdan);
		list_order=(PullToRefreshListView)getView().findViewById(R.id.list_order);
		list_order.setMode(Mode.BOTH);
		list_order.setOnRefreshListener(onrefresh);
		list_order.setOnItemClickListener(itemclicke);
		myOrder();
		btn_saoyisao=(ImageButton)getView().findViewById(R.id.btn_saoyisao);
		btn_saoyisao.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(mContext, ScanActivity.class);
				startActivity(intent);
			}
		});
		// 初始化合成对�?
				mTts = SpeechSynthesizer.createSynthesizer(mContext, mTtsInitListener);

				// 云端发音人名称列�?
				mCloudVoicersEntries = getResources().getStringArray(R.array.voicer_cloud_entries);
				mCloudVoicersValue = getResources().getStringArray(R.array.voicer_cloud_values);

				mToast = Toast.makeText(mContext,"",Toast.LENGTH_SHORT);

				setParam();
		handler.postDelayed(runnable, 10000);
	}
	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
//		myOrder();
	}
	
	/**
	 * 合成回调监听�?
	 */
	private SynthesizerListener mTtsListener = new SynthesizerListener() {
		@Override
		public void onSpeakBegin() {
			//			showTip("�?始播�?");
		}

		@Override
		public void onSpeakPaused() {
			//			showTip("暂停播放");
		}

		@Override
		public void onSpeakResumed() {
			//			showTip("继续播放");
		}

		@Override
		public void onBufferProgress(int percent, int beginPos, int endPos,
				String info) {
			// 合成进度
			//			mPercentForBuffering = percent;
			//			showTip(String.format(getString(R.string.tts_toast_format),
			//					mPercentForBuffering, mPercentForPlaying));
		}

		@Override
		public void onSpeakProgress(int percent, int beginPos, int endPos) {
			// 播放进度
			//			mPercentForPlaying = percent;
			//			showTip(String.format(getString(R.string.tts_toast_format),
			//					mPercentForBuffering, mPercentForPlaying));
		}

		@Override
		public void onCompleted(SpeechError error) {
			if (error == null) {
				//				showTip("播放完成");
			} else if (error != null) {
				showTip(error.getPlainDescription(true));
			}
		}

		@Override
		public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {

		}
	};

	private void showTip(final String str) {
		mToast.setText(str);
		mToast.show();
	}

	private void TTs() {
		String sayContext = "您有新的订单请及时处理";
		int code = mTts.startSpeaking(sayContext, mTtsListener);
		//		/** 
		//		 * 只保存音频不进行播放接口,调用此接口请注释startSpeaking接口
		//		 * text:要合成的文本，uri:�?要保存的音频全路径，listener:回调接口
		//		*/
		//		String path = Environment.getExternalStorageDirectory()+"/tts.pcm";
		//		int code = mTts.synthesizeToUri(text, path, mTtsListener);

		if (code != ErrorCode.SUCCESS) {
			if(code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED){
				//未安装则跳转到提示安装页�?
				//mInstaller.install();
			}else {
				showTip("语音合成失败,错误码: " + code);	
			}
		}
	}
	
	/**
	 * 初始化监听�??
	 */
	private InitListener mTtsInitListener = new InitListener() {
		@Override
		public void onInit(int code) {
			if (code != ErrorCode.SUCCESS) {
				showTip("初始化失败,错误码："+code);
			} else {
				// 初始化成功，之后可以调用startSpeaking方法
				// 注：有的�?发�?�在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成�?
				// 正确的做法是将onCreate中的startSpeaking调用移至这里
			}		
		}
	};

	/**
	 * 参数设置
	 * @param param
	 * @return 
	 */
	private void setParam(){
		// 清空参数
		mTts.setParameter(SpeechConstant.PARAMS, null);
		// 根据合成引擎设置相应参数
		if(mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
			mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
			// 设置在线合成发音�?
			mTts.setParameter(SpeechConstant.VOICE_NAME,voicer);
		}else {
			mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
			// 设置本地合成发音�? voicer为空，默认�?�过语音+界面指定发音人�??
			mTts.setParameter(SpeechConstant.VOICE_NAME,"");
		}
		//设置合成语�??
		mTts.setParameter(SpeechConstant.SPEED, "50");
		//设置合成音调
		mTts.setParameter(SpeechConstant.PITCH, "50");
		//设置合成音量
		mTts.setParameter(SpeechConstant.VOLUME,"50");
		//设置播放器音频流类型
		mTts.setParameter(SpeechConstant.STREAM_TYPE,"3");

		// 设置播放合成音频打断音乐播放，默认为true
		mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");

		// 设置合成音频保存路径，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
		mTts.setParameter(SpeechConstant.PARAMS,"tts_audio_path="+Environment.getExternalStorageDirectory()+"/test.pcm");
	}
	
	
	private Handler handler = new Handler();
	private Runnable runnable = new Runnable() {
		public void run() {
			try {
				this.update();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			handler.postDelayed(this, 60000);// 间隔60秒刷新一�?
		}
		void update() throws IOException {
			onrefresh.onPullDownToRefresh(list_order);
//			myOrder();
		}
	}; 
	
	/** 上下拉刷�? */
	private OnRefreshListener2<ListView> onrefresh = new OnRefreshListener2<ListView>() {

		@Override
		public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
			offset = 0;
			orderlist.clear();
			if (httpTools == null) {
				httpTools = new HttpTools(mContext);
			}
			httpTools.order(token, page + "", offset + "","0", "0",new JsonMyOrder());
			if (NetWorkUtil.isNetwork(mContext) == false) {
				Toast.makeText(mContext,  "当前网络不可用", Toast.LENGTH_SHORT).show();
				list_order.onRefreshComplete();
				return;
			}
		}

		@Override
		public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
			offset += page;
			httpTools.order(token, page + "", offset + "", "0","0",new JsonMyOrder());
			if (httpTools == null) {
				httpTools = new HttpTools(mContext);
			}
			if (NetWorkUtil.isNetwork(mContext) == false) {
				Toast.makeText(mContext,  "当前网络不可用", Toast.LENGTH_SHORT).show();
				list_order.onRefreshComplete();
				return;
			}
			// setSection();
			// adapter.notifyDataSetChanged();
		}

	};
	
	private OnItemClickListener itemclicke = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view,final int position,
				long id) {
			Intent intent = new Intent();
			intent.putExtra("id", orderlist.get(position-1).getId());
			intent.setClass(mContext, OrderDetailActivity.class);
			startActivity(intent);
		}
	};
	
	/**所有订单*/
	private void myOrder() {
		if(NetWorkUtil.isNetwork(mContext)==false)
		{
			Toast.makeText(mContext, "当前网络不可用", Toast.LENGTH_SHORT).show();
			return;
		}
		SharedPreferences sp = mContext.getSharedPreferences("spReg",
				Context.MODE_PRIVATE);
		token = sp.getString("token", "");
		if (httpTools == null) {
			httpTools = new HttpTools(mContext);
		}
		httpTools.order(token, page + "", offset + "", "0","0",new JsonMyOrder());
	}
	
	private class JsonMyOrder extends JsonHttpResponseHandler {
		@Override
		public void onSuccess(int statusCode, Header[] headers,
				JSONObject response) {
			super.onSuccess(statusCode, headers, response);
			Log.e("lh", "JsonMyOrder=="+response.toString());
			try {
				boolean code = response.getBoolean("code");
				if (code == true) {
					JSONObject object = response.getJSONObject("data");
//					String isnew = object.getString("isnew");
					JSONArray array = object.getJSONArray("orders");
					for (int i = 0; i < array.length(); i++) {
						JSONObject object2 = array.getJSONObject(i);
						String id = object2.getString("id");
						String dayno = object2.getString("dayno");
						String receive_time = object2.getString("receive_time");
						state = object2.getString("state");
						String name = object2.getString("name");
						String phone = object2.getString("phone");
						String address = object2.getString("address");
						String paymodeid = object2.getString("paymodeid");
						String recmode = object2.getString("recmode");
						String dada_distance = object2.getString("dada_distance");
						String dada_fee = object2.getString("dada_fee");
						String dada_status=object2.getString("dada_status");
						if(state.equals("null")){
							Toast.makeText(mContext, "没有订单", Toast.LENGTH_SHORT).show();
						}else if(state.equals("1")){
							TTs();
						}
						orderlist.add(new OrderEntity(id, receive_time,
								dayno,state, name, phone, address,recmode,
								paymodeid,dada_distance,dada_fee,dada_status));
					}
					if(orderlist.size()==0){
						tv_dingdan.setVisibility(View.VISIBLE);
					}else{
						tv_dingdan.setVisibility(View.GONE);
					}
						adapter = new OrderAdapter(mContext, orderlist);
						list_order.setAdapter(adapter);
						list_order.getRefreshableView().setSelection(offset);
						list_order.onRefreshComplete();
				} else {
					String msg = response.getString("msg");
					Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
				}
//				list_order.onRefreshComplete();
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

	}
	
	public class OrderAdapter extends BaseAdapter{
		Context context;
		ArrayList<OrderEntity> list;
		HttpTools httpTools=null;
		
		public OrderAdapter(Context context,
			ArrayList<OrderEntity> list) {
			super();
			this.context = context;
			this.list = list;
		}
		@Override
		public int getCount() {
			return list.size();
		}
		@Override
		public Object getItem(int position) {
			return list.get(position);
		}
		@Override
		public long getItemId(int position) {
			return 0;
		}

		@SuppressLint("ResourceAsColor")
		@Override
		public View getView(final int position, View view, ViewGroup parent) {
			final Handler handler;
			if (view == null) {
				handler = new Handler();
				view = LayoutInflater.from(context).inflate(
						R.layout.item_order, null);
				handler.tv_id=(TextView)view.findViewById(R.id.tv_id);
				handler.tv_time=(TextView)view.findViewById(R.id.tv_time);
				handler.tv_user=(TextView)view.findViewById(R.id.tv_user);
				handler.tv_address=(TextView)view.findViewById(R.id.tv_address);
				handler.tv_phone=(TextView)view.findViewById(R.id.tv_phone);
				handler.tv_state=(TextView)view.findViewById(R.id.tv_state);
				handler.btn_queren=(Button)view.findViewById(R.id.btn_queren);
				handler.btn_dayin=(Button)view.findViewById(R.id.btn_dayin);
				handler.btn_xiangqing=(Button)view.findViewById(R.id.btn_xiangqiang);
				handler.tv_qucanfangshi=(TextView)view.findViewById(R.id.tv_qucanfangshi);
				view.setTag(handler);
			} else {
				handler = (Handler) view.getTag();
			}
			handler.tv_id.setText(list.get(position).getOrderno());
			handler.tv_time.setText(list.get(position).getReceive_time());
			handler.tv_phone.setText(list.get(position).getPhone());
			handler.tv_user.setText(list.get(position).getName());
			
			if(list.get(position).getState().equals("1")){
				handler.tv_state.setText("待确认");
				handler.btn_queren.setText("接单");
				handler.btn_queren.setEnabled(true);
			}else if(list.get(position).getState().equals("2")){
				handler.tv_state.setText("待取餐");
				
				if (list.get(position).getRecmode().equals("2")){
					if(list.get(position).getDada_status().equals("2")){
						handler.btn_queren.setText("订单已发布");
					
					}else{
						handler.btn_queren.setText("发送给达达");
					}
				}else {
					handler.btn_queren.setText("已接单");
				}
			}else if(list.get(position).getState().equals("3")){
				handler.tv_state.setText("已完成");
				handler.btn_queren.setText("已完成");
				handler.btn_queren.setEnabled(false);
			}
			if (list.get(position).getAddress().equals("null")||list.get(position).getAddress().equals("")) {
				handler.tv_address.setText("无");
			}else {
				handler.tv_address.setText(list.get(position).getAddress());
			}
			if(list.get(position).getRecmode().equals("1")){
				handler.tv_qucanfangshi.setText("店内自提");
			}else if (list.get(position).getRecmode().equals("2")){
				handler.tv_qucanfangshi.setText("送货上门");
			}else if (list.get(position).getRecmode().equals("3")){
			handler.tv_qucanfangshi.setText("堂吃");
		}
			handler.btn_xiangqing.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent();
					intent.setClass(context, BluetoothActivity.class);
					intent.putExtra("id", list.get(position).getId());
//					intent.putExtra("state", list.get(position).getState());
					intent.putExtra("address", list.get(position).getAddress());
					context.startActivity(intent);
				}
			});
			handler.btn_dayin.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent();
					intent.setClass(context, WifiPrintActivity.class);
					intent.putExtra("address", list.get(position).getAddress());
					intent.putExtra("id", list.get(position).getId());
					context.startActivity(intent);
				}
			});
			
			handler.btn_queren.setOnClickListener(new OnClickListener() {
				SharedPreferences sp = context.getSharedPreferences("spReg",
						Context.MODE_PRIVATE);
				String token = sp.getString("token", "");
				@Override
				public void onClick(View v) {
					
					if(list.get(position).getState().equals("2")&&list.get(position).getRecmode().equals("2")){
//							Dadadialog(position);	
						if(list.get(position).getDada_status().equals("2")){
							return;
						}else{
							queryfee(position);
						}
					}else {
						Jiedan(position);
					}
					
				}
			});
			return view;
		}
		private void Jiedan(final int index){
			if (httpTools == null) {
				httpTools = new HttpTools(context);
			}
			httpTools.yiwancheng(token, list.get(index).getId(),"2",list.get(index).getPaymodeid(),
					new JsonHttpResponseHandler() {

				@Override
				public void onSuccess(int statusCode, Header[] headers,
						JSONObject response) {
					super.onSuccess(statusCode, headers, response);
					try {
						boolean code = response.getBoolean("code");
						String msg = response.getString("msg");
						
						if (code == true) {
							Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
							//										view.setBackgroundResource(R.drawable.shouchang1);
//							myOrder();
							list.get(index).setState("2");
							notifyDataSetChanged();
							
						} else {
							Toast.makeText(context, "已接单", Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			});
		}
		
		private void queryfee(final int index){
			if (httpTools == null) {
				httpTools = new HttpTools(context);
			}
			httpTools.queryfee(token, list.get(index).getId(),
					new JsonHttpResponseHandler(){

				@Override
				public void onSuccess(int statusCode, Header[] headers,
						JSONObject response) {
					super.onSuccess(statusCode, headers, response);
					try {
						boolean code=response.getBoolean("code");
						String msg=response.getString("msg");
						if(code){
							JSONObject data=response.getJSONObject("data");
							final String distance=data.getString("distance");
							String fee=data.getString("fee");
							final String deliveryNo=data.getString("deliveryNo");
							dialog("地址:"+distance+"米\n费用:"+fee+"元",
									index,context,deliveryNo,
									list.get(index).getId());
						}else{
							Toast.makeText(getActivity(), msg, 
									Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
					
				}
				
				@Override
				public void onFailure(int statusCode, Header[] headers,
					String responseBody, Throwable e) {
					super.onFailure(statusCode, headers, responseBody, e);
					Toast.makeText(getActivity(), "获取达达信息失败", 
					Toast.LENGTH_SHORT).show();
				}
			});
		
			
		}

		class Handler {
			TextView tv_id;
			TextView tv_time;
			TextView tv_user;
			TextView tv_address;
			TextView tv_phone;
			TextView tv_state;
			TextView tv_qucanfangshi;
			Button btn_queren;
			Button btn_dayin;
			Button btn_xiangqing;
		}
	}
	
	
	private void dialog(String msg,final int position,
			final Context context,final String deliveryNo,final String id){
		CustomDialog dialog=new CustomDialog(getActivity(), "是否发送给达达",
				msg,
				null, null, new DialogClickListener() {
					public void onDialogClick(int btn) {
						if(btn==1){
							addAfterQuery(position,context,deliveryNo,id);
						}
					}
				});
		dialog.show();
	}
	
	private void addAfterQuery(final int position,final Context context,
			String deliveryno,String orderid){
		if (httpTools == null) {
			httpTools = new HttpTools(context);
		}
		httpTools.addAfterQuery(token, deliveryno, orderid,
            new JsonHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					boolean code=response.getBoolean("code");
					String msg=response.getString("msg");
					if(code){
						orderlist.get(position).setDada_status("2");
						adapter.notifyDataSetChanged();
					}
					Toast.makeText(getActivity(), msg, 
							Toast.LENGTH_SHORT).show();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
				@Override
			public void onFailure(int statusCode, Header[] headers,
				String responseBody, Throwable e) {
				super.onFailure(statusCode, headers, responseBody, e);
				Toast.makeText(context, "发送失败", 
						Toast.LENGTH_SHORT).show();
			}
		});
	}
	
}
